package com.fpt.edu.vn.h2tv.api.pub;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.fpt.edu.vn.h2tv.common.ElementName;
import com.fpt.edu.vn.h2tv.dao.EntityManagerHelper;
import com.fpt.edu.vn.h2tv.dao.ITbAccountDAO;
import com.fpt.edu.vn.h2tv.dao.TbAccountDAO;
import com.fpt.edu.vn.h2tv.dao.entity.TbAccount;
import com.fpt.edu.vn.h2tv.dto.UserInfo;
import com.fpt.edu.vn.h2tv.service.UserService;
import com.fpt.edu.vn.h2tv.service.UserSessionData;
import com.fpt.edu.vn.h2tv.utils.ApiUtils;

@Path("book/authen")
public class AuthenAPI {

    @POST
    @Produces(MediaType.APPLICATION_XML)
    @Path("/login")
    public Response authenUser(@Context HttpServletRequest request, @FormParam("userName") String userName,
            @FormParam("passWord") String password) {
        // System.out.println("vao");
        if (userName != null && !userName.equals("") && password != null && !password.equals("")) {
            UserInfo info = doAuthen(userName, password);
            if (info != null) {
                request.getSession().setAttribute(ElementName.USER_INFO, info);
                UserSessionData userSessionData = ApiUtils.getUserSessionData(request.getSession());
                userSessionData.setUserInfo(info);
                return buildResponseOK(MediaType.APPLICATION_XML,Status.OK,info);
            }
        }
        return buildUnAuthorizationMessage("Authentication Fail");
    }
    
    @PUT
    @Produces(MediaType.APPLICATION_XML)
    @Path("/register")
    public Response registerUser(@Context HttpServletRequest request,
            @FormParam("userName") String userName,
            @FormParam("passWord") String password,
            @FormParam("email") String email,
            @FormParam("firstName") String firstName,
            @FormParam("lastName") String lastName,
            @FormParam("phone") String phone,
            @FormParam("address") String address) {
        
        UserInfo info = UserService.registerUser(userName, password, email, firstName, lastName, phone, address);
        request.getSession().setAttribute(ElementName.USER_INFO, info);
        UserSessionData userSessionData = ApiUtils.getUserSessionData(request.getSession());
        userSessionData.setUserInfo(info);
        return buildResponseOK(MediaType.APPLICATION_XML,Status.OK,info);
    }
    @POST
    @Produces(MediaType.APPLICATION_XML)
    @Path("/changePassword")
    public Response changePassword(@Context HttpServletRequest request,
            @FormParam("oldPassword") String oldPassword,
            @FormParam("newPassword") String newPassword) {
        
        UserInfo info = (UserInfo) request.getSession().getAttribute(ElementName.USER_INFO);
        if(info==null){
            return buildUnAuthorizationMessage("you have no permission");
        }else{
            String userName = info.getUserName();
            TbAccountDAO dao = new TbAccountDAO();
            TbAccount account =  dao.getUserInfoByUserNamePassword(userName, oldPassword);
            if(account==null){
                return buildResponseOK(MediaType.TEXT_PLAIN, Status.NOT_FOUND, "Please check again your password");
            }else{
                account.setPassword(newPassword);
                EntityManagerHelper.beginTransaction();
                dao.update(account);
                EntityManagerHelper.commit();
                return buildResponseOK(MediaType.TEXT_PLAIN, Status.OK, "Updated successful");
            }
            
        }
    }
    

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("/info")
    public Response getUserInfo(@Context HttpServletRequest request) {
        // System.out.println("vao");
        UserInfo info = (UserInfo) request.getSession().getAttribute(ElementName.USER_INFO);
        if (info != null) {
            return buildResponseOK(MediaType.APPLICATION_XML,Status.OK,info);
        } else {
            return buildUnAuthorizationMessage("Authentication Fail");
        }
    }
    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("/checkExits")
    public String check(@Context HttpServletRequest request,
            @QueryParam("userName") String userName) {
        TbAccountDAO dao = new TbAccountDAO();
        List<TbAccount> account = dao.findByUsername(userName);
        if(account!=null&&account.size()>0){
            return "<value>true</value>";
        }else{
            return "<value>false</value>";
        }
    }
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/logout")
    public Response doLogout(@Context HttpServletRequest request) {
       request.getSession().setAttribute(ElementName.USER_INFO,null);
       UserSessionData userSessionData = ApiUtils.getUserSessionData(request.getSession());
       userSessionData.setUserInfo(null);
       return buildResponseOK(MediaType.TEXT_PLAIN, Status.OK, "log out successful");
    }

    private Response buildUnAuthorizationMessage(String message) {
        return Response.ok(message).type(MediaType.TEXT_PLAIN).status(Status.UNAUTHORIZED)
//                .header("Access-Control-Allow-Origin", "http://localhost")
//                .header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,TRACE,HEAD,CONNECT")
//                .header("Access-Control-Allow-Credentials", "true")
//                .header("Access-Control-Allow-Headers", "X-Accept-Charset,X-Accept,Content-Type,Authorization,REFERER")
                .build();
    }
    private Response buildResponseOK(String contentType, Status status, Object object) {
        return Response.ok(object)
                .status(status)
//                .header("Access-Control-Allow-Origin", "http://localhost")
//                .header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,TRACE,HEAD,CONNECT")
//                .header("Access-Control-Allow-Credentials", "true")
//                .header("Access-Control-Allow-Headers", "X-Accept-Charset,X-Accept,Content-Type,Authorization,REFERER")
                .type(contentType).build();
    }


    private UserInfo doAuthen(String userName, String password) {
        ITbAccountDAO dao = new TbAccountDAO();
        TbAccount account = dao.getUserInfoByUserNamePassword(userName, password);
        if (account != null) {
            UserInfo info = new UserInfo();
            info.setUserName(account.getUsername());
            info.setRole(account.getRole());
            info.setUserId(account.getUserid());
            info.setAvatar(account.getAvatar());
            info.setEmail(account.getEmail());
            return info;
        }

        return null;
    }
}
